package top.kaoshanji.p3ch13a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.security.auth.Subject;
import java.security.PrivilegedAction;

/**
 * 代码清单-p3ch13a-422页a：Subject类的doAsPrivileged方法的使用示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/8 10:20
 */
public class SubjectDoAs {

    private static final Logger logger = LogManager.getLogger(SubjectDoAs.class);

    public static void main(String[] args) {
        logger.info("...代码清单-p3ch13a-422页a：Subject类的doAsPrivileged方法的使用示例...");

        SubjectDoAs sda = new SubjectDoAs();
        sda.doAs();
    }

    public void doAs() {
        Subject subject = new Subject();
        UserPrincipal principal = new UserPrincipal("Alex");

        subject.getPrincipals().add(principal);
        subject.setReadOnly();

        String userHome = Subject.doAsPrivileged(subject, new PrivilegedAction<String>() {
            @Override
            public String run() {
                return System.getProperty("user.home");
            }
        }, null);

        System.out.println(userHome);
    }


}
